﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Runtime.ConstrainedExecution;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Documents;

namespace ABELGX
{
    public class Trans
    {
        public TransSet Set { get; set; }
        Port port1;
        Port port2;
        public Trans(TransSet set)
        {
            Set = set;
            port1 = new Port(set.Port1);
            port2 = new Port(set.Port2);
            port1.DataReceive += Port1_DataReceive;
            port2.DataReceive += Port2_DataReceive;
        }

        private void Port2_DataReceive(object sender, EventArgs e)
        {
            Send(port2,port1);
        }

        private void Port1_DataReceive(object sender, EventArgs e)
        {
            Send(port1, port2);
        }
        void Send(Port from,Port to)
        {
            bool trans_send = false;
            if (Set.Interval == 0 && Set.Length == 0)
            {
                trans_send = true;
            }
            else if (Set.Interval == 0 && Set.Length > 0)
            {
                if (from.BufferLength >= Set.Length)
                {
                    trans_send = true;
                }
            }
            else
            {
                if (DateTime.Now.Subtract(from.SendTime).TotalMilliseconds >= Set.Interval)
                {
                    if (from.BufferLength > 0)
                    {
                        trans_send = true;
                    }
                }
            }
            if (!trans_send)
            {
                return;
            }
            from.SendTime = DateTime.Now;
            byte[] data = new byte[from.BufferLength + 5];
            data[0] = 0xAA;
            data[1] = 0x55;
            data[2] = (byte)(from.BufferLength + 1);
            data[3] = CarCmd.CMD_SUBS;
            Array.Copy(from.Buffer, 0, data, 4, from.BufferLength);
            byte xor = data[2];
            int send_len = from.BufferLength + 2;
            for (int i = 3; i < send_len - 1; i++)
            {
                xor ^= data[i];
            }
            data[data.Length-1] = xor;
            from.Clear();
            to.Send(data);
        }
        public void Close()
        {
            port1.Close();
            port2.Close();
        }
    }
}
